﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.Data.OleDb;
using System.Data.SqlClient;

using MapInfo.Data;
using MapInfo.Mapping;
using MapInfo.Engine;
using MapInfo.Geometry;
using MapInfo.Styles;
using MapInfo.Tools;
using MapInfo.Windows.Controls;
using SkinSharp;
namespace MapX
{
    public partial class MapForm1 : Form
    {
        private String FileName;
        private String DefaultFileName = "AB_MAP.tab";
        private String room_key;

        public MapForm1()
        {
            InitializeComponent();

            SkinH_Net ss = new SkinH_Net();
            ss.AttachExt("Skins/Aero.she", null, 80, 80, 50);
            ss.SetAero(1);
            //ss.AttachEx("Skins/Aero.she", null);
            //ss.SetBackColor(this.textBox1.Handle, 0, 0, 0);
            //ss.AdjustAero(200, 0, 0, 100, 10, 10, 0, 0, 0);
            //ss.AdjustHSV(0, 255, 0);
            
            ss.LockUpdate(this.textBox1.Handle, 1);
            ss.LockUpdate(this.panel1.Handle, 1);
            ss.LockUpdate(this.panel2.Handle, 1);
            ss.LockUpdate(this.panel3.Handle, 1);
            ss.LockUpdate(this.mapToolBar1.Handle, 1);
            ss.LockUpdate(this.mapControl1.Handle, 1);
            //ss.LockUpdate(this.statusStrip1.Handle, 1);
            ss.LockUpdate(this.msg.Handle, 1);
            ss.LockUpdate(this.cloudDigitalClock1.Handle, 1);

            ss.SetMenuAlpha(200);
            ss.SetWindowAlpha(this.msg.Handle, 100);
            this.BackColor = Color.FromArgb(120, 120, 120);
            this.ForeColor = Color.FromArgb(0, 200, 120);
            this.panel2.BackColor = Color.FromArgb(250, 245, 250);
            this.panel3.BackColor = Color.FromArgb(220, 220, 220);
            this.mapToolBarButtonOpenTable.ImageIndex = 39; // 将我们的打开按钮对应上图标
            //mapControl1.Map.ViewChangedEvent += new ViewChangedEventHandler(Map_ViewChangedEvent);
            //Map_ViewChangedEvent(this, null);
            textBox1.Text = "请先加载地图!!";

            try
            {
                mapControl1.Map = Session.Current.MapFactory.CreateFromFile(@DefaultFileName, System.IntPtr.Zero, mapControl1.Size);
            }
            catch (System.IO.FileNotFoundException)
            {
                MessageBox.Show("无法打开AB_MAP.TAB\r\n你可通过手工加载打开它", "温馨提示");
            }
            finally
            {
                FileName = "AB_MAP";
                textBox1.Text =
                            "MapName:\t" + mapControl1.Map.Name + "\r\n" +
                            "FileName:\t" + FileName + "\r\n";
                
                this.mapToolBarButtonSelect.Pushed = true;
            }
        }

        void Map_ViewChangedEvent(object sender, ViewChangedEventArgs e)
        {
            // Display the zoom level
            Double dblZoom = Convert.ToDouble(String.Format("{0:E2}", mapControl1.Map.Zoom.Value));

            msg.Text = "缩放: " + dblZoom.ToString() + " " + CoordSys.DistanceUnitAbbreviation(mapControl1.Map.Zoom.Unit);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            int num = Convert.ToInt32(tb.Text.ToString());
            if(num==10)
            {
                MessageBox.Show("已经是最大了！");
                return;
            }
            else
            {
                num++;
            }
            this.tb.Text = num.ToString();
            if (num < 1 || num > 10) return;
            Distance previousZoom = this.mapControl1.Map.Zoom;
            mapControl1.Map.Zoom = new Distance(previousZoom.Value / (2 * 1), previousZoom.Unit);
        }

        private void button2_Click(object sender, EventArgs e)
        {
            int num = Convert.ToInt32(tb.Text.ToString());
            if(num==0)
            {
                MessageBox.Show("已经是最小了！");
                return;
            }
            else
            {
                num--;
            }
            this.tb.Text = num.ToString();
            Distance previousZoom = this.mapControl1.Map.Zoom;
            mapControl1.Map.Zoom = new Distance(previousZoom.Value * (2 * 1), previousZoom.Unit);
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Distance previousZoom = this.mapControl1.Map.Zoom;
            mapControl1.Map.Zoom = new Distance(previousZoom.Value * (2 * 1), previousZoom.Unit);
        }
        private void con_access(String key)
        {
            #region Access 2007
            Console.WriteLine("Access 2007");
            string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;";
            strConnection += @"Data Source=roominfo.accdb;";
            strConnection += "Persist Security Info=False";
            using (OleDbConnection objConnection = new OleDbConnection(strConnection))
            {
                objConnection.Open();
                String sql = "select * from room where room_id=" + key;
                OleDbDataAdapter myCommandd = new OleDbDataAdapter(sql, objConnection);
                DataSet ds = new DataSet();
                myCommandd.Fill(ds, "room");
                DataTable dt = ds.Tables["room"];
                DataRow[] dRow = dt.Select("room_id = " + key);
//                textBox1.Text = dRow[0]["lord"]+"\r\n";
                room_num.Text = dRow[0]["room_num"] + "\r\n";
                mem_info.Text = dRow[0]["members"] + "\r\n";
                room_info.Text = dRow[0]["room_info"] + "\r\n";
                lord.Text = dRow[0]["lord"] + "\r\n";
//                textBox1.Text = dt.Columns[0].ToString() + "\r\n" + dt.Columns[1].ToString() + "\r\n" + dt.Columns[2].ToString() + "\r\n" + dt.Columns[3].ToString();
                objConnection.Close();
            }
            #endregion
        }

        private void mapControl1_MouseClick(object sender, MouseEventArgs e)
        {
            if (this.mapToolBarButtonSelect.Pushed)
                mapControl1_MouseDoubleClick(sender, e);
        }

        private void mapControl1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (true == mapControl1.Map.Empty)
            {
                MessageBox.Show("请加载地图", "温馨提示");
                textBox1.Text = "请加载地图!!";
                return;
            }
            PointF DisplayPoint = new PointF(e.X, e.Y);
            DPoint MapPoint = new DPoint();

            DisplayTransform converter = this.mapControl1.Map.DisplayTransform;
            converter.FromDisplay(DisplayPoint, out MapPoint);

            try
            {
                Map _map = mapControl1.Map;
                Catalog _catalog = Session.Current.Catalog;
                Cursor.Current = Cursors.WaitCursor;

                //设置查找半径
                Distance d = MapInfo.Mapping.SearchInfoFactory.ScreenToMapDistance(_map, 3);
                SearchInfo si = MapInfo.Data.SearchInfoFactory.SearchNearest(MapPoint, _map.GetDisplayCoordSys(), d);
                IResultSetFeatureCollection irfc = _catalog.Search(FileName, si);//WORLD是地图名，可以改成变量
                
                Session.Current.Selections.DefaultSelection.Clear();
                Session.Current.Selections.DefaultSelection.Add(irfc);

                foreach (Feature f in irfc)
                {
                    if (f.ToString() != "")
                    {
                        textBox1.Text = 
                            "key:\t\t" + f.Key.ToString() + "\r\n" + 
                            "BaseTable:\t" + irfc.BaseTable.Alias + "\r\n" + 
                            "Table:\t\t" + f.Table + "\r\n" + 
                            "Feature:\t" + f.ToString() + "\r\n" +
                            "MapName:\t" + _map.Name + "\r\n" +
                            "FileName:\t" + FileName + "\r\n";
                        room_key = f.Key.ToString();
//                         if (room_key.Equals("1"))
//                             break;
                        con_access(room_key);
                    }
                }

                irfc.Clear();
            }
            finally
            {
                Cursor.Current = Cursors.Default;
            }
        }

        private void mapControl1_MouseMove(object sender, MouseEventArgs e)
        {
            PointF DisplayPoint = new PointF(e.X, e.Y);
            DPoint MapPoint = new DPoint();
            DisplayTransform converter = this.mapControl1.Map.DisplayTransform;
            converter.FromDisplay(DisplayPoint, out MapPoint);
            //toolStripStatusLabel1.Text = "";
            msg.Text = "DisplayPoint: " + e.X.ToString() + ", " + e.Y.ToString() + " Cursor Location: " + MapPoint.x.ToString() + ", " + MapPoint.y.ToString();
        }

        private void DoMapfromFile()
        {
            OpenFileDialog openFileDialog1 = new OpenFileDialog();
            openFileDialog1.Multiselect = true;
            openFileDialog1.CheckFileExists = true;
            openFileDialog1.DefaultExt = "TAB;GST;MWS";
            openFileDialog1.Filter =
                "全部地图文件(*.tab)(*.gst)(*.mws)|*.tab;*.gst;*.mws|" +
                "MapInfo Tables (*.tab)|*.tab|" +
                "MapInfo Geoset (*.gst)|*.gst|" +
                "MapInfo WorkSpace (*.mws)|*.mws|" +
                "全部 (*)|*";

            string strCantOpenList = null;
            if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
            {
                foreach (string filename in openFileDialog1.FileNames)
                {
                    try
                    {
                        Map map = Session.Current.MapFactory.CreateFromFile(filename, System.IntPtr.Zero, mapControl1.Size);
                        mapControl1.Map = map;

                        FileName = filename.Substring(filename.LastIndexOf('\\') + 1, filename.LastIndexOf('.') - filename.LastIndexOf('\\') - 1);
                        textBox1.Text = 
                            "MapName:\t" + map.Name + "\r\n" +
                            "FileName:\t" + FileName + "\r\n" +
                            "Path: " + filename + "\r\n";
                    }
                    catch (MapException me)
                    {
                        if (strCantOpenList == null)
                        {
                            strCantOpenList = me.Arg;
                        }
                        else
                        {
                            strCantOpenList = strCantOpenList + ", " + me.Arg;
                        }
                    }
                }
            }
            if (strCantOpenList != null)
            {
                MessageBox.Show("The following failed to open: " + strCantOpenList);
            }
        }

        private void write_port(String szWrite)//预留写串口接口
        {
            serialPort1.PortName = "COM1";
            serialPort1.BaudRate = 9600;
            serialPort1.Open();
            //            byte[] data = Encoding.Unicode.GetBytes(textBox1.Text);
            byte[] data = Encoding.Unicode.GetBytes(szWrite);
            string str = Convert.ToBase64String(data);
            serialPort1.WriteLine(str);
            MessageBox.Show("数据发送成功！", "系统提示");
            textBox1.Text = serialPort1.PortName + "数据接收成功！"; 
        }
        private String read_port()//预留读串口接口
        {
            byte[] data = Convert.FromBase64String(serialPort1.ReadLine());
            //           textBox2.Text = Encoding.Unicode.GetString(data);
            serialPort1.Close();
            MessageBox.Show("数据接收成功！", "系统提示");
            textBox1.Text = "数据接收成功！"; 
            return Encoding.Unicode.GetString(data);
        }

        private void mapToolBar1_ButtonClick(object sender, ToolBarButtonClickEventArgs e)
        {
            if (this.mapToolBarButtonOpenTable.Pushed)
            {
                DoMapfromFile();
                if (false == mapControl1.Map.Empty)
                {
                    this.mapToolBarButtonSelect.Enabled = true;
                    this.mapToolBarButtonSelectRect.Enabled = true;
                    this.mapToolBarButtonSelectRadius.Enabled = true;
                    this.mapToolBarButtonPan.Enabled = true;
                    this.mapToolBarButtonZoomIn.Enabled = true;
                    this.mapToolBarButtonZoomOut.Enabled = true;
                    this.mapToolBarButtonSelect.Pushed = true;
                }
                this.mapToolBarButtonOpenTable.Pushed = false;
            }
        }

        private void DB_Click(object sender, EventArgs e)
        {
            #region Access 2007
            string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;";
            strConnection += @"Data Source=roominfo.accdb;";
            strConnection += "Persist Security Info=False";
            using (OleDbConnection objConnection = new OleDbConnection(strConnection))
            {
                objConnection.Open();
                OleDbCommand cmd = objConnection.CreateCommand();
                cmd.CommandText = "select * from room where room_id=801";
                OleDbDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    room_num.Text = reader["room_id"] + "\r\n";
                    mem_info.Text = reader["members"] + "\r\n";
                    room_info.Text = reader["temperature"] + "\r\n";
                    lord.Text = reader["lord"] + "\r\n";
                    textBox1.Text = reader["room_id"] + "\r\n" + reader["members"] + "\r\n" + reader["room_info"] + "\r\n" + reader["lord"] + "\r\n";
                }
                objConnection.Close();
            }
            #endregion
            textBox1.Text = "XML message:\r\n";
            Tools tl = new Tools();
            tl.set_config("config.xml");
            textBox1.Text += "Port:" + tl.port + "\r\n";
            textBox1.Text += "BaudRate:" + tl.BaudRate + "\r\n";
        }

        private void plusMark1_Click(object sender, EventArgs e)
        {
            int num = Convert.ToInt32(tb.Text.ToString());
            if (num == 10)
            {
                MessageBox.Show("已经是最大了！");
                return;
            }
            else
            {
                num++;
            }
            this.tb.Text = num.ToString();
            if (num < 1 || num > 10) return;
            Distance previousZoom = this.mapControl1.Map.Zoom;
            mapControl1.Map.Zoom = new Distance(previousZoom.Value / (2 * 1), previousZoom.Unit);
        }
    }
}